import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:kxy_flutter_app/auth.dart';
import 'package:kxy_flutter_app/model/login_result.dart';
import 'package:shared_preferences/shared_preferences.dart';

class AuthModel with ChangeNotifier {
  final String _authKey = 'AUTHKEY';
  final String _authDateKey = 'AUTHDATEKEY';

  bool _isAuthed = false;
  DateFormat _format = new DateFormat('yyyy-MM-dd HH:mm:ss');
  get isAuthed => _isAuthed;

  Future<bool> authorizeFromCache() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    if (prefs.containsKey(_authKey) && prefs.containsKey(_authDateKey)) {
      // 检验时间
      var dateStr = prefs.getString(_authDateKey);
      var date = DateTime.parse(dateStr);
      var beforeDate = DateTime.now().add(Duration(days: -5));
      if (date.isBefore(beforeDate)) {
        prefs.remove(_authKey);
        prefs.remove(_authDateKey);
        return false;
      }

      var jsonStr = prefs.getString(_authKey);
      var json = jsonDecode(jsonStr);
      var loginResult = LoginResult.fromJson(json);

      Auth.instance.authorize(loginResult);
      this._isAuthed = true;
      return true;
    }

    prefs.remove(_authKey);
    prefs.remove(_authDateKey);
    return false;
  }

  Future authoize(LoginResult loginResult) async {
    // 登陆认证
    Auth.instance.authorize(loginResult);
    this._isAuthed = true;

    // 保存登陆信息
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var jsonStr = jsonEncode(loginResult.toJson());
    prefs.setString(_authKey, jsonStr);
    prefs.setString(_authDateKey, _format.format(DateTime.now()));

    notifyListeners();
  }

  Future unauthorize() async {
    // 退出登陆
    Auth.instance.unauthorize();
    this._isAuthed = false;

    // 删除登陆信息
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.remove(_authKey);
    prefs.remove(_authDateKey);

    notifyListeners();
  }
}
